package com.sikong.geomesa;

import com.sikong.configuration.Constant;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.opengis.feature.simple.SimpleFeatureType;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 这是一段用于示范GeoMesa-HBase读取数据的逻辑代码
 *
 * @author 梁超 / stan
 * @since 0.1.0
 * @Date 2022/03/27
 */
public class GetFeature {

    /**
     * 定义要读取的数据表，这里我们以读取微博数据为例
     */
    private final String catalog = "weiboData";

    /**
     * 此方法用于连接geomesa-hbase
     *
     * @return DataStore
     */
    private DataStore getDataStore() throws IOException {
        Map<String, String> params = new HashMap<>();

        params.put(Constant.ZK,Constant.ZK_HOST);
        params.put(Constant.HBASE_CATALOG,this.catalog);

        return DataStoreFinder.getDataStore(params);
    }

    /**
     * 此方法用于打印要素类名称和要素类属性表结构
     *
     * @return SimpleFeatureCollection
     */
    public SimpleFeatureCollection getFeatureType() throws IOException {
        DataStore dataStore = this.getDataStore();
        String[] typeNames = dataStore.getTypeNames();

        if (typeNames.length > 0) {
            System.out.println(Arrays.toString(typeNames) + " Detected !");
            SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeNames[0]);

            SimpleFeatureType schema = featureSource.getSchema();
            System.out.println("Header: \n" + schema);//属性表结构

            return featureSource.getFeatures();
        } else {
            System.out.println("Nothing here!");
            return null;
        }
    }

    /**
     * 此方法用于打印数据，考虑到一次只读一批数据，用iterator的思想加入if判断并break时会出现DoNotRetryExecption
     * 未找到处理方法，因此将iterator换为array，并按照索引切片取值
     *
     * @param featureArray 表中的要素数组
     * @param count 要查询的数量（从第一个开始）
     */
    public void readData(Object[] featureArray, int count) throws InterruptedException {

        for (int i = 0; i < count; i++) {
            Object o = featureArray[i];
            System.out.println(String.format("Data %d \n", i) + o);

            Thread.sleep(100);
        }
    }
}
